package net.lab1024.sa.admin.module.app.user;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import net.lab1024.sa.admin.module.app.user.domain.UserEntity;
import net.lab1024.sa.admin.module.app.user.domain.UserAddForm;
import net.lab1024.sa.admin.module.app.user.domain.UserQueryForm;
import net.lab1024.sa.admin.module.app.user.domain.UserUpdateForm;
import net.lab1024.sa.admin.module.app.user.domain.UserVO;
import net.lab1024.sa.admin.module.business.oa.enterprise.dao.EnterpriseDao;
import net.lab1024.sa.admin.module.business.oa.enterprise.domain.vo.EnterpriseVO;
import net.lab1024.sa.admin.module.system.login.domain.RequestEmployee;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.enumeration.EmployeeTypeEnum;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static net.lab1024.sa.admin.module.app.user.constant.UserConstants.APP_SALT_FORMAT;
import static net.lab1024.sa.admin.module.app.user.constant.UserConstants.INITIAL_PASSWORD;

/**
 * app小程序用户 Service
 *
 * @Author M
 * @Date 2024-10-18 20:45:17
 * @Copyright Transmute实验室
 */

@Service
public class UserService {

    private final UserDao userDao;

    private final EnterpriseDao enterpriseDao;

    public UserService(UserDao userDao, EnterpriseDao enterpriseDao) {
        this.userDao = userDao;
        this.enterpriseDao = enterpriseDao;
    }

    /**
     * 分页查询
     *
     * @param queryForm
     * @return
     */
    public PageResult<UserVO> queryPage(UserQueryForm queryForm, RequestEmployee requestUser) {
        Integer employeeType = requestUser.getEmployeeType();
        if (EmployeeTypeEnum.ENTERPRISE.getValue().equals(employeeType)) {
            queryForm.setEnterpriseId(requestUser.getEnterpriseId());
        }
        queryForm.setDeletedFlag(Boolean.FALSE);
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<UserVO> list = userDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 添加
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> add(UserAddForm addForm) {
        // 校验用户名查询
        LambdaQueryWrapper<UserEntity> wrapperByUserName = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getUserName, addForm.getUserName())
                .eq(UserEntity::getDeletedFlag, Boolean.FALSE)
                .last("limit 1");
        UserEntity userByUserName = userDao.selectOne(wrapperByUserName);
        if (userByUserName != null) {
            return ResponseDTO.userErrorParam("用户名已存在");
        }
        // 校验手机号
        LambdaQueryWrapper<UserEntity> wrapperByPhone = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getPhone, addForm.getPhone())
                .eq(UserEntity::getDeletedFlag, Boolean.FALSE)
                .last("limit 1");
        UserEntity userByPhone = userDao.selectOne(wrapperByPhone);
        if (userByPhone != null) {
            return ResponseDTO.userErrorParam("手机号已存在");
        }
        // 校验企业
        EnterpriseVO enterprise = enterpriseDao.getDetail(addForm.getEnterpriseId(), Boolean.FALSE);
        if (enterprise == null) {
            return ResponseDTO.userErrorParam("企业不存在");
        }

        UserEntity userEntity = SmartBeanUtil.copy(addForm, UserEntity.class);
        // 初始化密码
        userEntity.setPassword(getEncryptPwd(INITIAL_PASSWORD));
        userDao.insert(userEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     * @param updateForm
     * @return
     */
    public ResponseDTO<String> update(UserUpdateForm updateForm) {
        // 根据id查询用户
        UserEntity userById = userDao.selectById(updateForm.getUserId());
        if (userById == null) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }

        // 校验用户名
        UserEntity userByUserName = userDao.getByUserName(updateForm.getUserName());
        if (userByUserName != null && !updateForm.getUserId().equals(userByUserName.getUserId())) {
            return ResponseDTO.userErrorParam("用户名已存在");
        }

        // 校验手机号
        LambdaQueryWrapper<UserEntity> wrapperByPhone = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getPhone, updateForm.getPhone())
                .eq(UserEntity::getDeletedFlag, Boolean.FALSE)
                .ne(UserEntity::getUserId, updateForm.getUserId())
                .last("limit 1");
        UserEntity userByPhone = userDao.selectOne(wrapperByPhone);
        if (userByPhone != null) {
            return ResponseDTO.userErrorParam("手机号已存在");
        }

        // 校验企业
        EnterpriseVO enterprise = enterpriseDao.getDetail(updateForm.getEnterpriseId(), Boolean.FALSE);
        if (enterprise == null) {
            return ResponseDTO.userErrorParam("企业不存在");
        }

        UserEntity userEntity = SmartBeanUtil.copy(updateForm, UserEntity.class);
        userDao.updateById(userEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     */
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)){
            return ResponseDTO.ok();
        }

        userDao.batchUpdateDeleted(idList, true);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(Long userId) {
        if (null == userId){
            return ResponseDTO.ok();
        }

        userDao.updateDeleted(userId,true);
        return ResponseDTO.ok();
    }

    public static String getEncryptPwd(String password) {
        return DigestUtils.md5Hex(String.format(APP_SALT_FORMAT, password));
    }

    public ResponseDTO<String> resetPassword(Long userId) {
        if (userId == null){
            return ResponseDTO.userErrorParam("用户ID不能为空");
        }
        UserEntity userEntity = userDao.selectById(userId);
        if (userEntity == null){
            return ResponseDTO.userErrorParam("用户不存在，ID: " + userId);
        }
        // 根据ID更新初始密码
        LambdaUpdateWrapper<UserEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserEntity::getUserId, userId);
        String encryptPwd = getEncryptPwd(INITIAL_PASSWORD);
        wrapper.set(UserEntity::getPassword, encryptPwd);
        userDao.update(new UserEntity(), wrapper);
        return ResponseDTO.ok();
    }

    public UserEntity getByUserName(String userName) {
        return userDao.getByUserName(userName);
    }

    public UserEntity getById(Long requestUserId) {
        return userDao.selectById(requestUserId);
    }
}
